let { join } = require('path')
let filename = join(__dirname,'db.json')

let { readFile, writeFile} = require('fs')

function query(){
  readFile(filename,'utf-8',(err,data)=>{
    if(err) throw err;
    let res = JSON.parse(data)
    return res;
  })
}
// query();
function add(row){
  readFile(filename,'utf-8',(err,data)=>{
    if(err) throw err;
    let arr = JSON.parse(data);
    row.id = arr[arr.length-1].id + 1;
    arr.push(row);
    let str = JSON.stringify(arr);
    writeFile(filename,str,err=>{
      if(err) throw err;
      console.log("添加成功")
    })
  })
}
// add({heroName:'jacka',sex:'man',age:19});
function del(id){
  readFile(filename,'utf-8',(err,data)=>{
    if(err) throw err;
    let arr = JSON.parse(data);
    // let arrNew = arr.filter(item=>item.id !=id)
    let index = arr.findIndex(item=>item.id==id)
    if(index==-1){
      console.log('数据不存在')
      return 
    }
    let str = JSON.stringify(arrNew);
    writeFile(filename,str,err=>{
      if(err) throw err;
      console.log("删除成功")
    })
  })
}
// del(2);
function update(row){
  readFile(filename,'utf-8',(err,data)=>{
    if(err) throw err;
    let arr = JSON.parse(data);
    let index = arr.findIndex(item=>item.id==row.id)
    arr[index] = Object.assign(arr[index], row)
    let str = JSON.stringify(arr);
    writeFile(filename,str,err=>{
      if(err) throw err;
      console.log("更新成功")
    })
  })
}

update({id:1,heroName:"oo"})